package top.lshaci.learning.springboot.mybatisplus.config;

import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.extension.plugins.inner.TenantLineInnerInterceptor;
import net.sf.jsqlparser.expression.Expression;
import net.sf.jsqlparser.expression.Parenthesis;
import net.sf.jsqlparser.expression.operators.conditional.AndExpression;
import net.sf.jsqlparser.expression.operators.relational.EqualsTo;
import net.sf.jsqlparser.schema.Column;
import net.sf.jsqlparser.schema.Table;
import net.sf.jsqlparser.statement.insert.Insert;

/**
 * TenantAccountLineInnerInterceptor
 *
 * @author lshaci
 * @version 1.0.2
 * @since 1.0.2
 */
public class TenantAccountLineInnerInterceptor extends TenantLineInnerInterceptor {

    private final TenantAccountLineHandler tenantAccountLineHandler;

    public TenantAccountLineInnerInterceptor(TenantAccountLineHandler tenantAccountLineHandler) {
        super(tenantAccountLineHandler);
        this.tenantAccountLineHandler = tenantAccountLineHandler;
    }

    @Override
    protected void processInsert(Insert insert, int index, String sql, Object obj) {
        // 插入不处理, 使用 自动填充功能 填充数据
    }

    @Override
    public Expression buildTableExpression(final Table table, final Expression where, final String whereSegment) {
        if (tenantAccountLineHandler.ignoreTable(table.getName())) {
            return null;
        }
        AndExpression tenantAccount = new AndExpression(
                new EqualsTo(getAliasColumnTenant(table), tenantAccountLineHandler.getTenantId()),
                new EqualsTo(getAliasColumnAccount(table), tenantAccountLineHandler.getAccountId())
        );
        return new Parenthesis(tenantAccount);
    }


    /**
     * 租户字段别名设置
     * <p>tenant_id 或 tableAlias.tenant_id</p>
     *
     * @param table 表对象
     * @return 字段
     */
    protected Column getAliasColumnTenant(Table table) {
        return getAliasColumn(table, tenantAccountLineHandler.getTenantIdColumn());
    }

    /**
     * 账套字段别名设置
     * <p>account_id 或 tableAlias.account_id</p>
     *
     * @param table 表对象
     * @return 字段
     */
    protected Column getAliasColumnAccount(Table table) {
        return getAliasColumn(table, tenantAccountLineHandler.getAccountIdColumn());
    }

    /**
     * 字段别名设置
     * <p>columnName 或 tableAlias.columnName</p>
     *
     * @param table      表对象
     * @param columnName 列名
     * @return 字段
     */
    protected Column getAliasColumn(Table table, String columnName) {
        StringBuilder column = new StringBuilder();
        if (table.getAlias() != null) {
            column.append(table.getAlias().getName()).append(StringPool.DOT);
        }
        column.append(columnName);
        return new Column(column.toString());
    }
}
